package com.dpwgc.pan.interceptor;

import com.dpwgc.pan.utils.RedisUtil;
import com.dpwgc.pan.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;
import com.alibaba.fastjson.JSON;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


/**
 * 拦截器
 */
@Controller
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    RedisUtil redisUtil;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        /**
         * 请求头部：两个参数
         * @param userId 用户id
         * @param token 登录令牌
         */
        String userId = request.getHeader("userId");//用户id
        String token = request.getHeader("token");//token令牌

        ResultUtil resultUtil = new ResultUtil();

        //如果请求头部id值为空
        if (userId == null){
            resultUtil.setMsg("请登陆后访问");
            resultUtil.setCode(440);
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(resultUtil));
            writer.flush();
            return false;
        }

        //从redis中取出对应token令牌，进行匹配
        Object resToken = redisUtil.get(userId);
        String strToken = String.valueOf(resToken);

        //匹配token令牌
        if (strToken.equals(token)){
            return true;
        }else {
            resultUtil.setMsg("请登陆后访问");
            resultUtil.setCode(440);
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(resultUtil));
            writer.flush();
            return false;
        }
    }
}
